package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {

        //1. 把数据添加到mysql
        Boolean flag = addTaskToDB(task);

        //2. 如果添加到mysql成功就添加数据到redis
        if(flag){
            addTaskToRedis(task);
        }

        //3. 返回任务的id
        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;

        //更新数据库-删除taskinfo中的任务 并更新log日志表中的状态
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);
        if(null != task){
            removeTaskFromRedis(task);
            flag = true;
        }

        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     * 每次只能拉取一个消息
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        //1. 构建小key
        String key = type + "_" + priority;

        //拉取任务消息
        String json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if(StringUtils.isNotEmpty(json)){
            Task task = JSON.parseObject(json, Task.class);

            updateDb(task.getTaskId(), ScheduleConstants.EXECUTED);

            return task;
        }

        return null;
    }

    //从redis中删除一个任务
    private void removeTaskFromRedis(Task task) {
        //1. 构建小key
        String key = task.getTaskType() + "_" + task.getPriority();

        //2. 判断到底要到list中还是到zset中删除数据
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            //3. 删除数据 - list集合中的数据
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    //更新数据库
    private Task updateDb(long taskId, Integer status) {
        //删除任务数据
        taskinfoMapper.deleteById(taskId);

        //更新日志表中的状态
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(status);
        taskinfoLogsMapper.updateById(taskinfoLogs);

        //构建任务数据并返回
        Task task = new Task();
        BeanUtils.copyProperties(taskinfoLogs, task);
        task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        return task;
    }

    //如果添加到mysql成功就添加数据到redis
    private void addTaskToRedis(Task task) {
        //1. 构建redis的小key
        String key = task.getTaskType() + "_" + task.getPriority();
        //2. 获取未来5分钟的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5); //在当前的时间上加上5分钟
        long futrueTime = calendar.getTimeInMillis();

        //3. 判断是否要添加到list或者zset中
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= futrueTime){
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    /**
     * 把数据添加到mysql
     * @param task
     * @return
     */
    private Boolean addTaskToDB(Task task) {
        //1. 添加任务到taskinfo
        Taskinfo entity = new Taskinfo();
        BeanUtils.copyProperties(task, entity);
        entity.setExecuteTime(new Date(task.getExecuteTime()));

        int count = taskinfoMapper.insert(entity);

        //2. 添加任务日志到taskinfolog表
        TaskinfoLogs logs = new TaskinfoLogs();
        BeanUtils.copyProperties(task, logs);

        logs.setTaskId(entity.getTaskId());
        logs.setStatus(ScheduleConstants.SCHEDULED);
        logs.setVersion(1);
        logs.setExecuteTime(new Date(task.getExecuteTime()));

        int count1 = taskinfoLogsMapper.insert(logs);

        //3. 设置任务的id到task对象
        task.setTaskId(entity.getTaskId());

        return  count == 1 && count1 == 1;
    }

    /**
     * 每个一分钟定时的刷新zset中的数据到list集合中
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){

        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if(StringUtils.isNotEmpty(token)){
            log.info("每个一分钟定时任务开始执行了");

            //1. 找到未来所有的key
            Set<String> futurekeys = cacheService.scan("future_*");

            //2. 然后遍历每一个key
            for (String futurekey : futurekeys) {
                //3. 从每一个key所在的集合中找到已经到期的任务， 然后批量的把他们从zset集合拷贝到list集合
                Set<String> jsonSet = cacheService.zRangeByScore(futurekey, 0, System.currentTimeMillis());

                if(null != jsonSet && jsonSet.size() > 0){
                    String targetKey = ScheduleConstants.TOPIC + futurekey.split(ScheduleConstants.FUTURE)[1];

                    //管道拷贝
                    cacheService.refreshWithPipeline(futurekey, targetKey, jsonSet);
                }
            }
        }

    }


    @Scheduled(cron = "0 */5 * * * ?")
    @PostConstruct
    public void reloadData(){
        //1. 清楚redis的缓存
        clearCache();

        //2. 查询未来5分钟要执行的任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);

        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));

        //3. 判断是否为空
        if(null != taskinfoList && taskinfoList.size() > 0){
            //4. 遍历每一个任务 根据执行时间添加到list或者zset
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());

                addTaskToRedis(task);
            }
        }

        log.info("刷新数据库中未来5分钟要执行的任务成功");
    }

    private void clearCache(){
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");

        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
        log.info("清楚redis缓存成功");
    }
}
